<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import {
  ElButton,
  ElForm,
  ElRow,
  ElInput,
  ElSelect,
  ElOption,
  ElFormItem,
  ElCol,
  FormRules,
  ElMessageBox
} from 'element-plus'
import { useRouter } from 'vue-router'
import {
  createUsersApi,
  createHotelUsersApi,
  updateUsersApi,
  getUsersDetailApi,
  getUserByLoginNameApi,
  grantUserHotelApi
} from '@/api/user'
import { getConstantValuesApi } from '@/api/constant-value'
import { getGendersListApi } from '@/api/gender'
import { ConstantValue } from '@/api/constant-value/types'
import { Gender } from '@/api/gender/types'
import { User } from '@/api/user/types'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { FormItem } from '@/components/Form'
import { useValidator } from '@/hooks/web/useValidator'
import { useCreate } from '@/hooks/web/useCreate'
import { useSessionStore } from '@/store/modules/session'
import { useRoute } from 'vue-router'
import { onMounted, unref } from 'vue'

const { push } = useRouter()

const { required } = useValidator()

const back = () => {
  push('/user/index')
}

const instance: User = reactive(new User())
const route = useRoute()

const userTypes = ref<Array<ConstantValue>>([])
const userStatuses = ref<Array<ConstantValue>>([])
const genders = reactive<Array<Gender>>([])

const sessionStore = useSessionStore()
const readonly = ref(false)

const preSave = () => {
  instance.xfull_name = `${instance.xlast}${instance.xfirst}`
}

const { elFormRef, openMode, save, loading, postSave } = useCreate({
  instance,
  route,
  preSave,
  afterSave: back,
  createApi: createUsersApi,
  updateApi: updateUsersApi
})

const view_role = computed(() => sessionStore.getViewRole)

const rules = computed((): FormRules => {
  return {
    xlast: [required('请填写姓名')],
    xfirst: [required('请填写姓名')],
    xfull_name: [required('请填写姓名')],
    login_name: [required('请填写用户名')],
    password_new: [
      { required: openMode.value === 'CREATE' && !readonly.value, message: '请填写密码' }
    ],
    status: [required('请选择用户状态')]
  }
})

const title = computed(() => {
  return openMode.value === 'CREATE' ? '添加用户' : '编辑用户'
})

onMounted(async () => {
  getConstantValuesApi('userTypes', 'userTypesMap').then((res) => {
    userTypes.value = res.data.userTypes
  })

  getConstantValuesApi('userStatuses', 'userStatusesMap').then((res) => {
    userStatuses.value = res.data.userStatuses
  })

  getGendersListApi({ pageIndex: -1, order: 'sequence', disabled: 'N' }).then((res) => {
    Object.assign(genders, res.data.rows)
    if (openMode.value === 'CREATE') {
      if (genders.length > 0) {
        instance.gender_id = genders[0].id
      }
    }
  })

  if (openMode.value === 'UPDATE') {
    const { data } = await getUsersDetailApi(route.params.id as string)
    instance.init(data)
  }
})

const onLoginNameBlur = async () => {
  if (view_role.value === 'hotel') {
    const login_name = instance.login_name
    if (login_name) {
      const res = await getUserByLoginNameApi(login_name!)
      if (res && res.data) {
        ElMessageBox.confirm(`用户${login_name}已存在`, '用户名重复', {
          type: 'warning',
          confirmButtonText: '查看用户',
          cancelButtonText: '重新填写用户名',
          showClose: false,
          closeOnClickModal: false,
          closeOnHashChange: false,
          closeOnPressEscape: false
        })
          .then((confirm) => {
            console.log(confirm)
            readonly.value = true
            instance.init(res.data)
          })
          .catch(() => {
            instance.login_name = ''
          })
      }
    }
  }
}

// const resetUserForm = () => {
//   instance.init()
//   readonly.value = false
// }

const grantHotel = async () => {
  const res = await grantUserHotelApi({
    hotel_id: sessionStore.getHotelId,
    user_id: instance.id
  })

  if (res) {
    postSave()
  }
}

const saveHotelUser = async () => {
  const form = unref(elFormRef)
  await form?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true

      const res = await (openMode.value === 'CREATE'
        ? createHotelUsersApi(instance, sessionStore.getHotelId)
        : updateUsersApi(instance.id!, instance)
      ).finally(() => {
        loading.value = false
      })
      if (res) {
        postSave()
      }
    }
  })
}

const customSave = async () => {
  if (view_role.value === 'admin') {
    await save()
  } else {
    await saveHotelUser()
  }
}
</script>

<template>
  <ContentDetailWrap :title="title" @back="back">
    <template #right>
      <ElButton
        v-if="!readonly"
        v-hasPermi="['user:add', 'user:edit']"
        type="primary"
        :loading="loading"
        @click="customSave"
      >
        保存
      </ElButton>
      <ElButton
        v-if="readonly"
        v-hasPermi="'user:permission'"
        type="primary"
        :loading="loading"
        @click="grantHotel"
      >
        加入主体
      </ElButton>
    </template>

    <ElForm
      ref="elFormRef"
      :model="instance"
      label-width="100px"
      :rules="rules"
      :disabled="readonly"
    >
      <ElRow class="max-w-800px ml-auto mr-auto">
        <FormItem label="用户名" prop="login_name">
          <ElInput
            v-model="instance.login_name"
            maxlength="50"
            :disabled="openMode === 'UPDATE'"
            @blur="onLoginNameBlur"
          />
        </FormItem>

        <FormItem label="密码" prop="password_new">
          <ElInput
            v-model="instance.password_new"
            type="password"
            maxlength="50"
            :disabled="openMode === 'UPDATE'"
            show-password
            clearable
          />
        </FormItem>

        <FormItem label="中文名" prop="xlast">
          <ElCol :span="11">
            <ElFormItem prop="xlast">
              <ElInput v-model="instance.xlast" maxlength="50" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12" :offset="1">
            <ElFormItem prop="xfirst">
              <ElInput v-model="instance.xfirst" maxlength="50" />
            </ElFormItem>
          </ElCol>
        </FormItem>

        <FormItem label="英文名">
          <ElCol :span="11">
            <ElFormItem prop="last">
              <ElInput v-model="instance.last" maxlength="50" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12" :offset="1">
            <ElFormItem prop="first">
              <ElInput v-model="instance.first" maxlength="50" />
            </ElFormItem>
          </ElCol>
        </FormItem>

        <FormItem v-if="view_role === 'admin'" label="用户类型" prop="user_type">
          <ElSelect v-model="instance.user_type" :disabled="openMode === 'UPDATE'">
            <ElOption
              v-for="item of userTypes"
              :key="item.code"
              :value="item.code!"
              :label="item.name"
            />
          </ElSelect>
        </FormItem>

        <FormItem v-if="view_role === 'admin'" label="用户状态" prop="status">
          <ElSelect v-model="instance.status">
            <ElOption
              v-for="item of userStatuses"
              :key="item.code"
              :value="item.code!"
              :label="item.name"
            />
          </ElSelect>
        </FormItem>

        <FormItem label="手机" prop="mobile">
          <ElInput v-model="instance.mobile" maxlength="20" />
        </FormItem>

        <FormItem label="邮箱" prop="email">
          <ElInput v-model="instance.email" maxlength="50" />
        </FormItem>

        <FormItem label="部门" prop="department">
          <ElInput v-model="instance.department" clearable />
        </FormItem>

        <FormItem label="职位" prop="position">
          <ElInput v-model="instance.position" clearable />
        </FormItem>

        <FormItem label="性别" prop="gender_id">
          <ElSelect v-model="instance.gender_id" clearable>
            <ElOption v-for="item of genders" :key="item.id" :value="item.id!" :label="item.name" />
          </ElSelect>
        </FormItem>

        <FormItem :col-props="{ span: 24 }" label="备注" prop="reference">
          <ElInput v-model="instance.reference" clearable />
        </FormItem>
      </ElRow>
    </ElForm>
  </ContentDetailWrap>
</template>
